package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.RequestAndResultCode;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.bean.RecResuleBean;
import com.bjesc_b2c.app.appraiset.mvp.presenter.AddCarPresenter;
import com.bjesc_b2c.app.appraiset.mvp.presenter.impl.AddCarPresenterImpl;
import com.bjesc_b2c.app.appraiset.mvp.view.CarIdView;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.bjesc_b2c.app.appraiset.widget.dialog.AnalyseDialog;
import com.example.codeutils.utils.FileUtils;
import com.example.codeutils.utils.TimeUtils;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.util.MapUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.Bind;
import butterknife.OnClick;
import master_bean.BasicInfoBean;
import master_bean.DealerBean;
import rxretrofit_base.model.KeyBean;

import static com.bjesc_b2c.app.appraiset.R.id.edit_analysis;

public class AddCarSourceActivity extends BaseActivity implements CarIdView, AnalyseDialog.DealerDateListener, RadioGroup.OnCheckedChangeListener {

    @Bind(R.id.detectionDate)
    TextView detectionDatTv;
    @Bind(R.id.tv_dealer_name)
    TextView dealerNameTv;
    @Bind(R.id.tv_add_dealer)
    TextView daaDealerTv;
    @Bind(R.id.tv_market_name)
    TextView marketNameTv;
    @Bind(R.id.edit_dealer_name)
    EditText dealerNameEdit;
    @Bind(R.id.edit_contact_name)
    EditText bossNameEdit;
    @Bind(R.id.edit_dealer_phone)
    EditText bossphoneEdit;
    @Bind(R.id.view_add_derler)
    View adddealerLin;
    @Bind(R.id.edit_car_vinnum)
    EditText carVinEdit;
    @Bind(R.id.edit_floor)//楼层
            EditText dealerFloorEdit;
    @Bind(R.id.edit_house_number)//门牌号
            EditText houseNumberEdit;
    @Bind(R.id.edit_parking_spaces)//车位数
            EditText parkingSpacesEdit;
    @Bind(R.id.edit_monthly_sales)//月销量
            EditText monthlySalesEdit;
    @Bind(R.id.edit_financial)//金融渗透率
            EditText financialEdit;
    @Bind(R.id.edit_financial_channel)//现有金融渠道
            EditText financialChannelEdit;
    @Bind(R.id.edit_channel)//收车渠道
            EditText channelEdit;
    @Bind(R.id.edit_preference)//收车偏好
            EditText preferenceEdit;
    @Bind(edit_analysis)//商户分析
            EditText analysisEdit;
    @Bind(R.id.edit_remarks)//备注
            EditText remarksEdit;
    @Bind(R.id.edit_representative)//业务代表
            EditText representativeEdit;

    //单选布局
    @Bind(R.id.rg_kanche)
    RadioGroup kancheRg;
    @Bind(R.id.rg_youxin)
    RadioGroup youxinRg;
    //箭头
    @Bind(R.id.iv_dealer_info_arrow)
    View carInfoArrowIv;
    @Bind(R.id.tv_title)
    TextView titleTv;
    private BasicInfoBean infoBean;
    private DealerBean dealerBean;
    private String bossName = "";          //车行联系人姓名
    private String bossPhone = ""; //车行联系人电话
    private String carVin = "";      //车牌vin
    private String dealerAddress = "";//车行详细地址
    private String carForId = "";//车行id
    private String dealerName = "";//车行名
    private String marketId = "";//车市ID
    private String floor = "";//楼层
    private String house_number = "";//门牌号
    private String car_number = "";//车位数
    private String month_sale = "";//月均销量

    private String channel = "";//现有金融渠道
    private String penetration = "";//金融渗透率
    private int kcCombine = 0;//看车是否合作
    private int yxCombine = 0;//优信是否合作
    private String car_preference = "";//收车偏好
    private String car_channel = "";//收车渠道
    private String merchant_analysis = "";//商户分析
    private String description = "";//备注
    private AddCarPresenter carPresenter;
    private AnalyseDialog analyseDialog;
    private int changeCase;
    private String srString;
    private boolean hasGotToken = false;
    private static final int REQUEST_CODE_GENERAL_BASIC = 106;
    private AlertDialog.Builder alertDialog;
    @Override
    protected int getLayout() {
        return R.layout.activity_new_car_source;
    }


    @Override
    protected void initEventAndData() {
        titleTv.setText("新增车源");
        alertDialog = new AlertDialog.Builder(this);
        kancheRg.setOnCheckedChangeListener(this);
        youxinRg.setOnCheckedChangeListener(this);
        //给需要的文本框添加TextChangedListener方法
        carVinEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // 将输入的小写字母实时转换成大写
                if (changeCase == 0) {
                    srString = s.toString().toUpperCase();
                    if (s.toString().equals("")) {
                        changeCase = 0;
                    } else {
                        changeCase = 1;
                    }
                    s.clear();
                } else if (changeCase == 1) {
                    changeCase = 2;
                    s.append(srString);
                } else {
                    changeCase = 0;
                }
            }
        });
    }

    @Override
    protected void createPresenter() {
        carPresenter = new AddCarPresenterImpl(this);
//        initAccessTokenWithAkSk();
         String validTime = CustomSharedPreferences.getString(mContext, KeyBean.VALID_TIME.valueOf(), KeyBean.FILE_NAME.valueOf());
        if (validTime != null && TimeUtils.getNowTimeString(TimeUtils.YMD_PATTERN).equals(validTime)){
            initAccessToken();
        }else {
            if (validTime == null){
                initAccessToken();
            }else {
                OCR.getInstance().initWithToken(getApplicationContext(), CustomSharedPreferences.getString(mContext, KeyBean.BAIDU_TOKEN.valueOf(), KeyBean.FILE_NAME.valueOf()));
                hasGotToken = true;
            }
        }
    }

    @OnClick({R.id.btn_detection, R.id.rlty_add_dealer, R.id.iv_return, R.id.rlty_dealer_name,
            R.id.tv_add_dealer, R.id.tv_vinnum_sort, R.id.rela_market_layout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_detection://开始检测
                carPresenter.requestAddCarId(putInfo());
                break;
            case R.id.rlty_dealer_name://选择车源
                Intent intent = new Intent(AddCarSourceActivity.this, MarketActivity.class);
                intent.putExtra("TYPE", 2);
                startIntent(intent, RequestAndResultCode.BasicActivity_To_CarFromActivity);
                break;
            case R.id.rlty_add_dealer://
                if (adddealerLin.getVisibility() == View.VISIBLE) {
                    adddealerLin.setVisibility(View.GONE);
                    setTowardsBottomToTopTextDrawable(carInfoArrowIv);
                } else {
                    adddealerLin.setVisibility(View.VISIBLE);
                    setTowardsTopToBottomTextDrawable(carInfoArrowIv);
                }
                break;
            case R.id.rela_market_layout://选择车市
                Intent markIntent = new Intent(AddCarSourceActivity.this, MarketActivity.class);
                markIntent.putExtra("TYPE", 1);
                startIntent(markIntent, RequestAndResultCode.BasicActivity_To_SelectColorActivity);
                break;
            case R.id.tv_add_dealer://添加车行
                getAllEditText();
                if (!TextUtils.isEmpty(dealerNameEdit.getText().toString())) {
                    analyseDialog = new AnalyseDialog(AddCarSourceActivity.this, setDealer(), AnalyseDialog.TYPE_DEALER, this);
                } else {
                    showToast("车商名不能为空");
                }
                break;
            case R.id.tv_vinnum_sort://排重
                if (!checkTokenStatus()) {
                    return;
                }
                Intent intentCamera = new Intent(AddCarSourceActivity.this, CameraActivity.class);
                intentCamera.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtils.getSaveFile(getApplication()).getAbsolutePath());
                intentCamera.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                        CameraActivity.CONTENT_TYPE_GENERAL);
                startActivityForResult(intentCamera, REQUEST_CODE_GENERAL_BASIC);
                break;
            case R.id.iv_return:
                finish();
                break;
        }
    }

    private void getAllEditText() {
        dealerName = dealerNameEdit.getText().toString();
//      dealerAddress = dealerAddressEdit.getText().toString();
        bossName = bossNameEdit.getText().toString();
        bossPhone = bossphoneEdit.getText().toString();
        floor = dealerFloorEdit.getText().toString();//楼层
        house_number = houseNumberEdit.getText().toString();//门牌号
        car_number = parkingSpacesEdit.getText().toString();//车位数
        month_sale = monthlySalesEdit.getText().toString();//月均销量
        channel = financialChannelEdit.getText().toString();//现有金融渠道
        penetration = financialEdit.getText().toString();//金融渗透率
        car_preference = preferenceEdit.getText().toString();//收车偏好
        car_channel = channelEdit.getText().toString();//收车渠道
        merchant_analysis = analysisEdit.getText().toString();//商户分析
        description = remarksEdit.getText().toString();//备注
    }

    private DealerBean setDealer() {
        if (dealerBean == null) {
            dealerBean = new DealerBean();
        }
        dealerBean.setDealer_name(dealerName);
        dealerBean.setBoss(bossName);
        dealerBean.setPhone(bossPhone);
        dealerBean.setAddress(dealerAddress);
        dealerBean.setXin_che(yxCombine);
        dealerBean.setKan_che(kcCombine);
        dealerBean.setMarket_id(marketId);
        dealerBean.setFloor(floor);
        dealerBean.setHouse_number(house_number);
        dealerBean.setCar_number(car_number);
        dealerBean.setMonth_sale(month_sale);
        dealerBean.setFinancial_penetration(penetration);
        dealerBean.setFinancial_channel(channel);
        dealerBean.setCar_channel(car_channel);
        dealerBean.setCar_preference(car_preference);
        dealerBean.setMerchant_analysis(merchant_analysis);
        dealerBean.setDescription(description);
        return dealerBean;
    }

    private BasicInfoBean putInfo() {
        if (infoBean == null) {
            infoBean = new BasicInfoBean();
        }
        carVin = carVinEdit.getText().toString();
        infoBean.setVin_number(carVin);
        infoBean.setDealer_id(carForId);
        return infoBean;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RequestAndResultCode.CarFromActivity_ResultCode:  //车辆来源
                carForId = data.getStringExtra("carFofId");
                if (!TextUtils.isEmpty(data.getStringExtra("carForName"))) {
                    dealerNameTv.setText(data.getStringExtra("carForName"));
                }
                break;
            case RequestAndResultCode.SelectColorActivity_ResultCode:  //车市
                marketId = data.getStringExtra("marketId");
                if (!TextUtils.isEmpty(data.getStringExtra("marketName"))) {
                    marketNameTv.setText(data.getStringExtra("marketName"));
                }
                break;
            case Activity.RESULT_OK:
                if (requestCode == REQUEST_CODE_GENERAL_BASIC) {
                    showLoading();
                    RecognizeService.recGeneralBasic(FileUtils.getSaveFile(getApplicationContext()).getAbsolutePath(),
                            new RecognizeService.ServiceListener() {
                                @Override
                                public void onResult(String result) {
                                    String strVin = "";
                                    Gson gson = new Gson();
                                    RecResuleBean bean = gson.fromJson(result, RecResuleBean.class);
                                    Logger.d(bean.getLog_id());
                                    Logger.d(bean.getWords_result_num());
                                    if (bean.getWords_result_num() > 0) {
                                    for (int i = 0; i < bean.getWords_result().size(); i++) {
                                        strVin+=bean.getWords_result().get(i).getWords();
                                    }
                                }
                                    carVinEdit.setText(strVin.replaceAll(" ", ""));
                                    cancelLoading();
                            }

                                @Override
                                public void onError(String result) {
                                    cancelLoading();
                                    showToast(result);
                                }
                            });

                }
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            initAccessToken();
        } else {
            Toast.makeText(getApplicationContext(), "需要android.permission.READ_PHONE_STATE", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void getCarId(BasicInfoBean bean) {
        infoBean.setId(bean.getId());
        CustomSharedPreferences.saveString(AddCarSourceActivity.this, new MapUtil().put(KeyBean.CARID.valueOf(), bean.getId()).build(), KeyBean.FILE_NAME.valueOf());
        Intent intent = new Intent(AddCarSourceActivity.this, BasicInfoActivity.class);
        startIntent(intent, true);
    }

    @Override
    public void getDealerDate(String id) {
        carForId = id;
        dealerNameTv.setText(dealerNameEdit.getText().toString());
        adddealerLin.setVisibility(View.GONE);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (group.getId()) {
            case R.id.rg_kanche:
                kancheCheck(checkedId);
                break;
            case R.id.rg_youxin:
                youxinCheck(checkedId);
                break;
        }
    }


    private void kancheCheck(int checkedId) {
        switch (checkedId) {
            case R.id.rbtn_kx_yes:
                kcCombine = 2;
                break;
            case R.id.rbtn_kx_no:
                kcCombine = 3;
                break;
        }
    }

    private void youxinCheck(int checkedId) {
        switch (checkedId) {
            case R.id.rbtn_yx_yes:
                yxCombine = 2;
                break;
            case R.id.rbtn_yx_no:
                yxCombine = 3;
                break;
        }
    }


    private boolean checkTokenStatus() {
        if (!hasGotToken) {
            Toast.makeText(getApplicationContext(), "token还未成功获取", Toast.LENGTH_LONG).show();
        }
        return hasGotToken;
    }

    private void initAccessToken() {

        OCR.getInstance().initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                String token = accessToken.getAccessToken();
                Logger.d("token"+token);
                Logger.d("token"+accessToken.getLic());
                Logger.d("token"+accessToken.getExpiresIn());
                long time = System.currentTimeMillis()/1000;
                Date nowTime = new Date((time+accessToken.getExpiresIn())*1000);
                SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd");
                String validDate = sdFormatter.format(nowTime);
                Logger.d("token "+ time );
                Logger.d("token "+ validDate );
                CustomSharedPreferences.saveString(mContext, new MapUtil()
                        .put(KeyBean.BAIDU_TOKEN.valueOf(), token)
                        .put(KeyBean.VALID_TIME.valueOf(), validDate)
                        .build(), KeyBean.FILE_NAME.valueOf());
//                alertText("licence方式获取token成功", accessToken.getAccessToken()+"  "+accessToken.getLic()+" "+accessToken.getExpiresIn());
                hasGotToken = true;
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                alertText("licence方式获取token失败", error.getMessage());
            }
        }, getApplicationContext());
    }

//    private void initAccessTokenWithAkSk() {
//        OCR.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
//            @Override
//            public void onResult(AccessToken result) {
//                String token = result.getAccessToken();
//                Logger.d("token"+token);
//                Logger.d("token"+result.getLic());
//                Logger.d("token"+result.getExpiresIn());
//                hasGotToken = true;
//            }
//            @Override
//            public void onError(OCRError error) {
//                error.printStackTrace();
//                alertText("AK，SK方式获取token失败", error.getMessage());
//            }
//        }, getApplicationContext(), "9my2WfV29Swhlsw8tBiWCSXD", "Fv5WAq0AzBQX6moiDdCmWs84VoXWI2qq");
//    }
    //声明两个变量，在控制输入小写显示大写的时候用到

    /**
     * 箭头动画，上转下
     */
    private void setTowardsTopToBottomTextDrawable(View view) {
        ObjectAnimator oa = ObjectAnimator.ofFloat(view, "rotation", 0f, 180f);
        oa.setDuration(200);
        oa.start();
    }

    /**
     * 箭头动画，下转上
     */
    private void setTowardsBottomToTopTextDrawable(View view) {
        ObjectAnimator oa = ObjectAnimator.ofFloat(view, "rotation", 180f, 0f);
        oa.setDuration(200);
        oa.start();
    }

    /**
     * 设置车辆信息、手续信息、配置信息点击后的背景颜色为灰色
     *
     * @param v
     */
    private void changeBackgroundToGray(View v) {
        v.setBackgroundResource(R.color.bg);
    }

    /**
     * 设置车辆信息、手续信息、配置信息点击后的背景颜色为白色
     *
     * @param v
     */
    private void changeBackgroundToWhite(View v) {
        v.setBackgroundResource(R.color.colorWhite);
    }

    private void alertText(final String title, final String message) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                alertDialog.setTitle(title)
                        .setMessage(message)
                        .setPositiveButton("确定", null)
                        .show();
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放内存资源
        OCR.getInstance().release();
    }
}
